package com.chenshu.doc_searchengine.controller;

import com.chenshu.doc_searchengine.common.MyResponse;
import com.chenshu.doc_searchengine.model.Result;
import com.chenshu.doc_searchengine.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-05-03
 * Time：20:08
 */
@RestController
public class SearchController {
    //此处要加上索引对象的实例
    //同时要完成索引加载的工作

    @Autowired
    private SearchService searchService;

    /**
     *
     * @param query 查询词
     * @param pIndex 页码
     * @return 参数为空会抛异常，返回值-1， 页码越界会返回-2
     */
    @GetMapping("/search")
    public Object search(@RequestParam("query") String query, @RequestParam("pindex") Integer pIndex) {
        //非空判断
        if (query.isEmpty()) {
            return MyResponse.fail(-2, "非法传入空值");
        }
        if (pIndex < 1) {
            return MyResponse.fail(-2, "非法页码");
        }
        List<Result> results = searchService.searchResults(query, pIndex);
        if (results == null) {
            return MyResponse.fail(-2, "非法页码");
        }
        return results;
    }

    @GetMapping("/totalpage")
    public Integer totalPage(@RequestParam("query") String query) {
        return searchService.getTotalPage(query);
    }
}